<template>
  <div class="createPost-container">
    <el-form ref="dataForm" :rules="rules" :model="form" class="form-container">
      <el-form-item prop="label">
        <DictGroupInput ref="dictGroupInput" :value.sync="form.label" dict-group="fragment_label" placeholder="Label" />
      </el-form-item>
      <div class="createPost-main-container">
        <el-form-item prop="fragment">
          <MEditor ref="markdownEditor" v-model="form.fragment" height="400px" />
        </el-form-item>
      </div>
      <el-form-item>
        <el-button v-waves type="success" @click="submitForm">Save</el-button>
        <el-button v-show="!isEdit" v-waves @click="reset">Reset</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { createOrUpdateFragment } from '@/api/info/fragment'
import waves from '@/directive/waves' // waves directive
import MEditor from '@/views/components/MEditor'
import DictGroupInput from '@/views/components/DictGroupInput'

const defaultForm = {
  fragment: '',
  label: '',
  uid: 0
}
export default {
  name: 'Fragment',
  components: { DictGroupInput, MEditor },
  directives: { waves },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {},
      rules: {
        fragment: [{ required: true, message: 'fragment is required', trigger: 'blur' }],
        label: [{ required: true, message: 'label is required', trigger: 'change' }]
      },
      loading: false
    }
  },
  computed: {
    ...mapGetters(['uid'])
  },
  created() {
    console.log('created')
    if (this.isEdit) {
      const row = this.$route.params
      this.form = Object.assign({}, row, { label: row.label.toString() }, { createAt: undefined, modifyAt: undefined })
    } else {
      this.form = Object.assign({}, defaultForm, { uid: this.uid })
    }
  },
  methods: {
    submitForm() {
      console.log(this.form)
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.loading = true
          createOrUpdateFragment(this.form)
            .then(response => {
              this.$notify({
                title: 'Success',
                message: 'save successfully',
                type: 'success',
                duration: 2000
              })
              // 更新通用词典
              this.$refs.dictGroupInput.$emit('newDict', this.form.label)
              if (!this.isEdit) {
                this.reset()
              }
              this.$refs.dictGroupInput.$emit('reset', this.form.label)
            })
            .catch(() => {
              this.loading = false
            })
          this.loading = false
        }
      })
    },
    reset() {
      this.$refs['dataForm'].resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.createPost-container {
  padding: 20px;
  .filter-item {
    padding: 5px 5px 0 10px;
  }
}
</style>
